package com.honglu.backend.controller;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.honglu.backend.bo.UUserBo;
import com.honglu.backend.common.shiroToken.TokenManager;
import com.honglu.backend.service.impl.UUserServiceImpl;
import com.honglu.backend.utils.CodeUtils;
import com.honglu.backend.utils.JSONUtils;
import com.honglu.backend.utils.MyDES;
import com.honglu.shiro.ShiroToken;
import com.honglu.utils.DateUtils;

/**
 * 登录
 * @author tb
 *
 */
@Controller
@RequestMapping(value ="/backend/web/login")
public class LoginController {
	
	@Autowired
	private UUserServiceImpl userServiceImpl;
	
	private static Logger logger=Logger.getLogger(LoginController.class);
	
	/**
	 * 跳转到登录界面
	 * @return
	 */
	@RequestMapping(value = "index")
	public String index(){
		return "redirect:/index/login.html";
	}
	
	
	/**
	 * ajax请求登录 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/ajaxLogin.do")
	public void submitLogin(HttpServletRequest request, HttpServletResponse response, UUserBo userBo){
		try {
			ShiroToken shiroToken= new ShiroToken(userBo.getUserName(), MyDES.encryptBasedDes(userBo.getPassword()));
			SecurityUtils.getSubject().login(shiroToken);
			
			String ip = TokenManager.getSession().getHost();//ip地址
			userBo = new UUserBo();
			userBo.setId(TokenManager.getUserId());
			userBo.setIp(ip);
			userBo.setLastLoginTime(DateUtils.parseToDateTimeStr(new Date()));
			userServiceImpl.updateEntityById(userBo);
			JSONUtils.toJSON(response, CodeUtils.SUCCESS);
			return ;
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage());
			JSONUtils.toJSON(response, CodeUtils.FAIL);
		}
		
	}
	
	
	/**
	 * 退出
	 * @return
	 */
	@RequestMapping(value="/logout",method =RequestMethod.GET)
	public String logout(){
		try {
			//退出
			SecurityUtils.getSubject().logout();
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return "redirect:/index/login.html";
		}
		return "redirect:/index/login.html";
	}
	
}
